#!/bin/bash

if [ 0 -eq $(find -iname *.gcda | wc -l) ]
then
  exit 0
fi

gcov --source-prefix ${TRAVIS_BUILD_DIR} --preserve-paths --relative-only $(find -iname *.gcda) 1>/dev/null || exit 0

cat >coverage.json <<EOF
{
  "service_job_id": "${TRAVIS_JOB_ID}",
  "service_name": "travis-ci",
  "source_files": [
EOF

for file in include*.gcov
do
  path=$(echo ${file} | sed -re 's%#%\/%g; s%.gcov$%%')
  cat >>coverage.json <<EOF
    {
      "name": "${path}",
      "source_digest": "$(md5sum ${TRAVIS_BUILD_DIR}/${path} | awk '{ print $1 }')",
      "coverage": [$(tail -n +3 ${file} | cut -d ':' -f 1 | sed -re 's%^ +%%g; s%-%null%g; s%^[#=]+$%0%;' | tr $'\n' ',' | sed -re 's%,$%%')]
    },
EOF
done

mv coverage.json coverage.json.tmp
cat >coverage.json <(head -n -1 coverage.json.tmp) <(echo -e "    }\n  ]\n}")
curl -F json_file=@coverage.json https://coveralls.io/api/v1/jobs
